package com.example.bluetoothclicker

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.activity.result.contract.ActivityResultContracts
import android.widget.Toast
import com.example.bluetoothclicker.bluetoothreceiver.BluetoothEventHandler
import com.example.bluetoothclicker.debug.DebugActivity
import com.example.bluetoothclicker.func.BluetoothConnectionManager
import com.example.bluetoothclicker.bluetoothreceiver.BluetoothReceiver
import com.example.bluetoothclicker.func.BluetoothService
import com.example.bluetoothclicker.normal.T9BluetoothManager
import com.example.bluetoothframework.connection.ConnectionModule

class MainActivity : AppCompatActivity() {

    private var bluetoothService: BluetoothService? = null
    private var isServiceBound = false
    private lateinit var eventHandler: BluetoothEventHandler


    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as? BluetoothService.BluetoothBinder
            bluetoothService = binder?.getService()
            isServiceBound = true

            // 启动蓝牙服务端
            bluetoothService?.startServer()
            Toast.makeText(this@MainActivity, "蓝牙服务端已启动", Toast.LENGTH_SHORT).show()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            bluetoothService = null
            isServiceBound = false
            Toast.makeText(this@MainActivity, "蓝牙服务端启动失败", Toast.LENGTH_SHORT).show()
        }
    }

    // 权限请求
    private val permissionRequest =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            val fineLocationPermissionGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true
            val coarseLocationPermissionGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true

            if (fineLocationPermissionGranted && coarseLocationPermissionGranted) {
                // 权限被授予后，展示
                displayHomeFragment()
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 检查权限
        checkPermissions()

        T9BluetoothManager.initialize(this)
        ConnectionModule.initialize(this)

        // 初始化 BluetoothEventHandler
        //eventHandler = BluetoothEventHandler(this)

        // 注册观察者
        //BluetoothReceiver.registerObserver(eventHandler)

        // 启动并绑定服务
        val intent = Intent(this, BluetoothService::class.java)
        bindService(intent, serviceConnection, BIND_AUTO_CREATE)

        // 默认显示主页
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.frame_container, HomeFragment.newInstance())
                .commit()
        }

        // 设置 BottomNavigationView 的点击事件
        val bottomNav: BottomNavigationView = findViewById(R.id.bottom_nav)
        bottomNav.setOnNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_home -> {
                    val fragment = HomeFragment.newInstance()
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment)
                        .commit()
                    true // 更新选中状态
                }
                R.id.nav_remote -> {
                    val fragment = RemoteFragment()
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment)
                        .commit()
                    true // 更新选中状态
                }
                R.id.nav_config -> {
                    val fragment = ConfigFragment()
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment)
                        .commit()
                    true // 更新选中状态
                }
                R.id.nav_debug -> {
                    // 启动 DebugActivity
                    val intent = Intent(this, DebugActivity::class.java)
                    startActivity(intent)
                    false // 不更新选中状态
                }
                else -> false // 默认返回 false
            }
        }



    }

    // 检查权限
    private fun checkPermissions() {
        val coarseLocationPermission = ContextCompat.checkSelfPermission(
            this, Manifest.permission.ACCESS_COARSE_LOCATION
        )
        val fineLocationPermission = ContextCompat.checkSelfPermission(
            this, Manifest.permission.ACCESS_FINE_LOCATION
        )

        if (coarseLocationPermission == PackageManager.PERMISSION_GRANTED &&
            fineLocationPermission == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予，直接显示
            displayHomeFragment()
        } else {
            // 请求权限
            permissionRequest.launch(
                arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
            )
        }
    }

    // 显示 HomeFragment
    private fun displayHomeFragment() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.frame_container, HomeFragment.newInstance())
            .commit()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (isServiceBound) {
            unbindService(serviceConnection)
        }
        BluetoothConnectionManager.releaseResources()
        BluetoothReceiver.unregisterObserver(eventHandler)
    }

}
